package edu.dut.yz.webdemo.service;


import edu.dut.yz.webdemo.bean.Result;
import edu.dut.yz.webdemo.bean.User;
import edu.dut.yz.webdemo.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserService {
    @Autowired
    UserMapper usermapper;

    public Result login(User userin){
        Result result=new Result();
        try {
            User user = usermapper.getUserByUsername(userin.getUsername());
            if(user==null){
                result.setMsg("用户未注册");
                //跳转到注册页面
            } else if (user.getPassword().equals(userin.getPassword())) {
                result.setMsg("登录成功");
                result.setSuccess(true);
                result.setDetails(user);
            } else {
                result.setMsg("用户名或密码错误");
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    public Result regist(User userin){
        Result result=new Result();
        try{
            if(userin.getUsername()==""||userin.getPassword()==""){
                result.setMsg("请输入用户名密码");
                return result;
            }
            if(userin.getUsername().length()<2||userin.getUsername().length()>8||userin.getPassword().length()<2||userin.getPassword().length()>8){
                result.setMsg("用户名和密码应多于两位，少于八位");
                return result;
            }
            User user = usermapper.getUserByUsername(userin.getUsername());
            if(user==null){
                usermapper.regist(userin);
                result.setMsg("注册成功");
                result.setSuccess(true);
            }else{
                result.setMsg("用户名已存在");
            }
        }catch(Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

}
